<?php

namespace Common\Model;

use Think\Model;

/**
 * 商品 sku 组合与属性关联表
 */
class GoodsSkuCombDefModel extends Model {

    protected $_auto = array(/* array(完成字段1,完成规则,[完成条件,附加规则]) */
        array('addTime', 'time', 1, 'function')
    );  // 自动完成定义

    /**
     * 添加单个信息
     * @return type
     */

    public function addSkuCombDef($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->add();
        }
        return $rt;
    }

    /**
     * 更新信息(注意$data一定要有主键id,若$data为空，则默认是对$_POST数组处理)
     * @return type
     */
    public function updateSkuCombDef($data = '') {
        $rt = false;
        if ($this->create($data)) {
            $rt = $this->save();
        }
        return $rt;
    }

    /**
     * 删除(批量)
     */
    public function deleteSkuCombDef($ids, $where = '') {

        if ($ids && strlen($ids) > 0) {
            $where = "combID in ( $ids )";
        } else if (!$ids && empty($where)) {
            $this->error = "无选定数据";
            return false;
        }
        return $this->where($where)->delete();
    }

    /**
     * 根据属性id得到skuID
     * @param type $defIDStr
     * @return type
     */
    public function getSkuIDByDefID($defIDStr) {
        return $this->where("defID in ( $defIDStr )")->getField('skuID', TRUE);
    }

    /**
     * 根据 skuID 联表查得 属性列表
     * @param type $skuID
     */
    public function getSkuDefNameBySkuID($skuID) {
        $pre = C("DB_PREFIX");
        $result = M("GoodsSkuCombDef cm")
                        ->field("ur.defID defID,ur.name name")
                        ->join("LEFT JOIN $pre" . "goods_sku_def ur on cm.defID = ur.defID ")
                        ->where("cm.skuID = $skuID ")->select();
        return $result;
    }
    
    /**
     * 根据 skuID 查得 defID
     * @param type $skuID
     */
    public function getDefIDBySkuID($skuID) {
       $rt = $this->where("skuID = $skuID")->getField('defID', TRUE);
       if($rt) {
           return implode(',', $rt);
       } else {
           return '';
       }
    }

}
